package top.zywork.strategy.order;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.zywork.constant.CommonConstant;
import top.zywork.dto.OrderPayDTO;
import top.zywork.dto.RefundOrderDTO;
import top.zywork.enums.*;
import top.zywork.exception.GlobalException;
import top.zywork.ext.dos.GraphicOrderExtDO;
import top.zywork.ext.dos.GraphicWalletDetailsExtDO;
import top.zywork.ext.dos.GraphicWalletExtDO;
import top.zywork.ext.service.GraphicOrderExtService;
import top.zywork.ext.service.GraphicWalletDetailsExtService;
import top.zywork.ext.service.GraphicWalletExtService;
import top.zywork.security.SecurityUtils;
import top.zywork.weixin.PayResult;
import top.zywork.weixin.RefundResult;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;

/**
 * 图文店打印
 * @author Animo
 * @Date 2020/11/29
 * @Blog http://www.ljyanimo.com
 */
@Service
@Slf4j
public class GraphicOrderStrategyService implements OrderService {

    @Autowired
    private BaseOrder baseOrder;

    @Autowired
    private GraphicOrderExtService graphicOrderExtService;

    @Autowired
    private GraphicWalletExtService graphicWalletExtService;

    @Autowired
    private GraphicWalletDetailsExtService graphicWalletDetailsExtService;



    /**
     * 当前打印回调地址
     */
    private static String payNotifyUrl = CommonConstant.DOMAIN + "/wx-pay/goods-order/wx-pay-notify/" + PayOrderEnum.DY.getName();

    /**
     * 打印取消订单回调地址
     */
    private static String refundNotifyUrl = CommonConstant.DOMAIN + "/wx-pay/goods-order/wx-refund-notify/" + RefundOrderEnum.DY_REFUND.getName();

    @Override
    public OrderPayDTO orderValidation(String orderId) {
        // 查询订单 未激活订单以及待支付订单
        GraphicOrderExtDO graphicOrderExtDO = graphicOrderExtService.getOne(new QueryWrapper<GraphicOrderExtDO>().eq("order_id", orderId)
                .eq("user_id", SecurityUtils.getJwtUser().getUserId())
                .eq("pay_status", PayStatusEnum.TO_BE_PAID.getCode())
                .eq("is_active", CommonConstant.IS_ACTIVE_FALSE));
        if(graphicOrderExtDO == null){
            throw new GlobalException("支付订单号有误");
        }
        return  new OrderPayDTO(graphicOrderExtDO.getPayAmount(),payNotifyUrl);
    }

    @Override
    public RefundOrderDTO refundValidation(String orderId) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void wxPaySuccessNotify(PayResult payResult) {
        log.info("打印下单支付成功回调：{}" ,payResult.toString());

        String now = LocalDate.now().toString();
        String time = String.valueOf(System.currentTimeMillis());
        String code = now.substring(2).replace("-","") + "-" + time.substring(time.length() - 4);

        JSONObject attachJsonObj = JSONObject.parseObject(payResult.getAttach());
        Long userId = attachJsonObj.getLong("userId");
        String orderIdAndNos = attachJsonObj.getString("orderIdAndNos");
        GraphicOrderExtDO orderExtDO = graphicOrderExtService.getOne(new QueryWrapper<GraphicOrderExtDO>().eq("order_id", orderIdAndNos));

        BigDecimal amount = new BigDecimal(payResult.getTotalFee() / 100.0).setScale(2, BigDecimal.ROUND_HALF_UP);

        // 设置支付状态
        orderExtDO.setPayStatus(PayStatusEnum.HAVE_TO_PAY.getCode());

        // 设置数据已激活可以查看
        orderExtDO.setIsActive(CommonConstant.IS_ACTIVE_TRUE);

        // 设置下单时间
        orderExtDO.setPlaceOrderTime(new Date());

        // 设置微信的订单号
        orderExtDO.setWxOrder(payResult.getTransactionId());

        // 设置取件码
        orderExtDO.setTakeCode(code);

        graphicOrderExtService.updateById(orderExtDO);

        // 保存用户账目表
        baseOrder.saveAccountDetail(userId, payResult.getTransactionId(), IncomeOutgoingTypeEnum.OUTGOING.getValue(), amount.negate(), AccountTypeEnum.PRINT.getValue(), orderIdAndNos);

        // 平台账目表 打印 收入
        baseOrder.savePlatformAccountDetail(userId, payResult.getTransactionId(), AccountTypeEnum.PRINT.getValue(),amount ,orderIdAndNos);

        // 保存当前图文店收入总余额
        GraphicWalletExtDO graphicWalletExtDO = graphicWalletExtService.getById(orderExtDO.getGraphicId());
        graphicWalletExtDO.setUsableRmbBalance(graphicWalletExtDO.getUsableRmbBalance().add(amount.negate()));

        // 保存当前图文店收入明细
        GraphicWalletDetailsExtDO graphicWalletDetailsExtDO = new GraphicWalletDetailsExtDO();
        graphicWalletDetailsExtDO.setCreateTime(new Date());
        graphicWalletDetailsExtDO.setGraphicId(orderExtDO.getGraphicId());
        graphicWalletDetailsExtDO.setIsActive(CommonConstant.IS_ACTIVE_TRUE);
        graphicWalletDetailsExtDO.setUsableRmbBalance(amount);
        graphicWalletDetailsExtDO.setOrderId(orderExtDO.getOrderId());
        graphicWalletDetailsExtDO.setWaterNo(orderExtDO.getWxOrder());
        graphicWalletDetailsExtService.save(graphicWalletDetailsExtDO);
    }

    @Override
    public void wxPayFailNotify(PayResult payResult) {

    }

    @Override
    public void wxRefundSuccessNotify(RefundResult refundResult) {

    }

    @Override
    public void wxRefundFailNotify(RefundResult refundResult) {

    }

    public static void main(String[] args) {
        String x = LocalDate.now().toString();

        System.out.println(x.substring(2,x.length()).replace("-",""));
    }
}
